import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/Check.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';

import '../../../Util/DateUtil.dart';
import '../../../Util/HttpGo.dart';
import 'ClassChangeConfirm.dart';

class ClassChange extends StatefulWidget {
  Function() onChangeDone;

  ClassChange({required this.onChangeDone});

  @override
  State<StatefulWidget> createState() {
    return _ClassChange();
  }
}

class _ClassChange extends State<ClassChange> {
  int selectedIndex = -1;

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getClassList();
    });
    super.initState();
  }

  List<dynamic> courseList = [];

  getClassList() {
    HttpGo(context).get("/Lesson/GetChangeLessonList?studentId=${Global.studentId}", {}, (data) {
      courseList = data["courseList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  ///　isDiffPrize：是否需顯示補差額課程(true/false)
  bool isDiffPrize = false;

  switchDiffPrize() {
    isDiffPrize = !isDiffPrize;
    setState(() {});
    if (selectedIndex >= 0) getLanguageList();
  }

  ///清空選擇 - 可在調用getLanguageList時同步執行
  clearChooser() {
    language = {};
    teacherGroup = {};
    lessonTime = "";
    changeLesson = {};
    setState(() {});
  }

  ///選擇語言
  List<dynamic> languageList = [];
  dynamic language = {};

  getLanguageList() {
    clearChooser();
    var orderId = courseList[selectedIndex]["purchaseOrderId"];
    HttpGo(context).get("/Lesson/GetLanguageOption?purchaseOrderId=${orderId}&isDiffPrize=${isDiffPrize}", {}, (data) {
      languageList = data["languageOptionList"];
    }, (code, error) => showToast(error));
  }

  chooseLanguage() {
    FocusManager.instance.primaryFocus?.unfocus();
    showWheelDialog2(context, "", languageList, "language", (index) {
      language = languageList[index];

      getLTList();
      lessonTime = ""; //清空分鐘

      getCLList();
      changeLesson = {}; //清空待換課程

      getTGList();
      teacherGroup = {}; //清空師資別

      setState(() {});
    });
  }

  ///選擇師資別
  List<dynamic> teacherGroupList = [];
  dynamic teacherGroup = {};

  getTGList() {
    var orderId = courseList[selectedIndex]["purchaseOrderId"];
    var languageId = language["languageId"];
    if (orderId == null || languageId == null) {
      teacherGroupList.clear();
      return;
    }
    HttpGo(context).get("/Lesson/GetTeacherGroup?purchaseOrderId=${orderId}&isDiffPrize=$isDiffPrize&languageId=$languageId", {}, (data) {
      teacherGroupList = data["teacherGroupList"];
    }, (code, error) => showToast(error));
  }

  chooseTG() {
    FocusManager.instance.primaryFocus?.unfocus();
    showWheelDialog2(context, "", teacherGroupList, "nationalityGroup", (index) {
      teacherGroup = teacherGroupList[index];

      getLTList();
      lessonTime = ""; //清空分鐘

      getCLList();
      changeLesson = {}; //清空待換課程

      setState(() {});
    });
  }

  ///選擇分鐘
  List<dynamic> lessonTimeList = [];
  String lessonTime = "";

  getLTList() {
    var orderId = courseList[selectedIndex]["purchaseOrderId"];
    var languageId = language["languageId"];
    var nationalityGroup = teacherGroup["nationalityGroupItemId"];
    if (orderId == null || languageId == null || nationalityGroup == null) {
      lessonTimeList.clear();
      return;
    }
    HttpGo(context).get(
        "/Lesson/GetLessonTime?purchaseOrderId=$orderId&isDiffPrize=$isDiffPrize&languageId=$languageId&nationalityGroup=$nationalityGroup",
        {}, (data) {
      lessonTimeList = data["lessonTimeList"];
    }, (code, error) => showToast(error));
  }

  chooseLT() {
    FocusManager.instance.primaryFocus?.unfocus();
    showWheelDialog(context, "", lessonTimeList, (index) {
      lessonTime = lessonTimeList[index].toString();

      getCLList();
      changeLesson = {}; //清空待換課程

      setState(() {});
    });
  }

  ///選擇待換課程
  List<dynamic> changeLessonList = [];
  dynamic changeLesson = {};

  getCLList() {
    var orderId = courseList[selectedIndex]["purchaseOrderId"];
    var languageId = language["languageId"];
    var nationalityGroup = teacherGroup["nationalityGroupItemId"];

    if (orderId == null || languageId == null || nationalityGroup == null || lessonTime.isEmpty) {
      changeLessonList.clear();
      return;
    }
    HttpGo(context).get(
        "/Lesson/GetLessonName?purchaseOrderId=$orderId&isDiffPrize=$isDiffPrize&languageId=$languageId&nationalityGroup=$nationalityGroup"
        "&lessonTime=$lessonTime",
        {}, (data) {
      changeLessonList = data["lessonNameList"];
    }, (code, error) => showToast(error));
  }

  chooseCLesson() {
    FocusManager.instance.primaryFocus?.unfocus();
    showWheelDialog2(context, "", changeLessonList, "lessonName", (index) {
      changeLesson = changeLessonList[index];
      setState(() {});
    });
  }

  ///點擊我要換課
  String fromLessonCount = "";

  changeLessonClick() {
    if (fromLessonCount == "") {
      showToast("請輸入欲更換的堂數");
      return;
    }
    var toLessonId = changeLesson["lessonId"] ?? 0;
    if (selectedIndex < 0 || toLessonId == 0) {
      return;
    }
    PageUtil().openReplace(
        context,
        ClassChangeConfirm(
            fromOrder: courseList[selectedIndex],
            fromLessonCount: int.parse(fromLessonCount),
            toLesson: changeLesson,
            onChangeDone: widget.onChangeDone));
  }

  @override
  Widget build(BuildContext context) {
    print("fromLessonCount:$fromLessonCount");
    return MyPage(
        "換課",
        Container(
            child: Column(children: [
          Expanded(
              child: ListView.builder(
                  itemCount: courseList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ItemClassChange(
                      selectedIndex == index,
                      data: courseList[index],
                      et_value: fromLessonCount,
                      onTap: (value) {
                        fromLessonCount = value;
                        selectedIndex = index;
                        getLanguageList();
                      },
                      onChanged: (value) {
                        fromLessonCount = value;
                        print("fromLessonCount:$fromLessonCount");
                      },
                    );
                  })),
          Container(
              decoration: Global.getWhiteBg_shadow(0, MyColor.Black50),
              padding: EdgeInsets.all(8),
              child: Column(children: [
                Row(children: [
                  GestureDetector(
                      onTap: switchDiffPrize,
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                          margin: EdgeInsets.all(8),
                          height: 17,
                          width: 17,
                          decoration: Global.getBg(isDiffPrize ? MyColor.Orange : Color(0xffccd1d3), 10),
                          child: isDiffPrize ? LocalImage("check.png", padding: EdgeInsets.all(1)) : Container())),
                  Text("顯示補差額課程")
                ]),
                Row(children: [
                  Expanded(child: ChooserBox(language["language"], hintText: "課程語言", onTap: chooseLanguage)),
                  Expanded(
                      child: ChooserBox(teacherGroup["nationalityGroup"],
                          hintText: "師資別", margin: EdgeInsets.fromLTRB(8, 0, 8, 0), onTap: chooseTG)),
                  Expanded(child: ChooserBox(lessonTime, hintText: "課程分鐘", onTap: chooseLT)),
                ]),
                ChooserBox(changeLesson["lessonName"], hintText: "欲換課程", margin: EdgeInsets.fromLTRB(0, 8, 0, 16), onTap: chooseCLesson),
                // Row(children: [
                //   Expanded(child: Text("單堂金額：", textAlign: TextAlign.end, style: TextStyle(color: MyColor.C7D, fontSize: 16))),
                //   Container(
                //       width: 100,
                //       alignment: Alignment.centerRight,
                //       child: Text("328 元", style: TextStyle(color: MyColor.C7D, fontSize: 16)))
                // ]),
                // Row(children: [
                //   Expanded(child: Text("轉換堂數：", textAlign: TextAlign.end, style: TextStyle(color: MyColor.C7D, fontSize: 16))),
                //   Container(
                //       width: 100, alignment: Alignment.centerRight, child: Text("12 堂", style: TextStyle(color: MyColor.C7D, fontSize: 16)))
                // ]),
                // Row(children: [
                //   Expanded(child: Text("差額：", textAlign: TextAlign.end, style: TextStyle(color: MyColor.C7D, fontSize: 16))),
                //   Container(
                //       width: 100, alignment: Alignment.centerRight, child: Text("28 元", style: TextStyle(color: MyColor.C7D, fontSize: 16)))
                // ]),
                Container(height: 1, color: Color(0xffdee2e6), margin: EdgeInsets.fromLTRB(0, 8, 0, 16)),
                Row(mainAxisSize: MainAxisSize.min, children: [
                  TextBtn("取消", height: 36, width: 100, style: TextStyle(color: MyColor.Orange), onTap: () {
                    PageUtil().back(context);
                  }),
                  Button("我要換課", height: 36, bgColor: MyColor.Orange, width: 120, radius: 4, onTap: changeLessonClick)
                ])
              ]))
        ])),
        bgColor: MyColor.F8,
        resizeToAvoidBottomInset: false);
  }
}

class ItemClassChange extends StatelessWidget {
  bool check;
  Function(String value)? onTap;
  Function(String value)? onChanged;
  dynamic data;
  String? et_value;
  TextEditingController controller = TextEditingController();

  ItemClassChange(this.check, {this.onTap, this.onChanged, this.data, this.et_value});

  @override
  Widget build(BuildContext context) {
    String endTime = getStrTime(getTimeByUtc(data["endTime"]), DateUtil.YMD);
    controller.text = check ? (et_value ?? "") : "";
    return Container(
        height: 100,
        color: check ? Color(0xffffeade) : MyColor.White,
        margin: EdgeInsets.only(bottom: 8),
        padding: EdgeInsets.fromLTRB(0, 8, 12, 8),
        child: Row(children: [
          GestureDetector(
              onTap: () {
                onTap?.call(controller.text);
              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                  margin: EdgeInsets.all(24),
                  height: 17,
                  width: 17,
                  decoration: Global.getBg(check ? MyColor.Orange : Color(0xffccd1d3), 10),
                  child: check ? LocalImage("check.png", padding: EdgeInsets.all(1)) : Container())),
          Expanded(
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              Text("#${data["purchaseOrderId"]}", style: TextStyle(fontSize: 12, color: MyColor.Blue, fontWeight: FontWeight.bold)),
              Text("$endTime", style: TextStyle(fontSize: 12, color: MyColor.C9)),
            ]),
            Text("${data["displayName"]}", style: TextStyle(fontSize: 15, color: MyColor.Blue)),
            Row(children: [
              Text("剩餘堂數：${data["lessonTotalCount"]}", style: TextStyle(fontSize: 13, color: MyColor.C7D)),
              Container(width: 44),
              Text("欲更換的堂數：", style: TextStyle(fontSize: 13, color: MyColor.C7D)),
              Container(
                  height: 28,
                  width: 52,
                  padding: EdgeInsets.fromLTRB(4, 0, 4, 0),
                  decoration: BoxDecoration(
                      color: check ? Colors.white : MyColor.F3,
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                      border: Border.all(width: 1, color: MyColor.C9)),
                  child: NormalInput(
                      inputType: NormalInput.Number, controller: controller, enable: check, fontColor: MyColor.C7D, onChanged: onChanged)),
            ])
          ]))
        ]));
  }
}
